<?php
declare (strict_types=1);

namespace app\api\controller;

use think\facade\View;
use think\response\Json;
use app\common\model\Cart as CartModel;

class Cart extends Base
{
    public function index()
    {
        $map = ['uid' => $this->user->id];
        $list = CartModel::getList($map, false, 'update_time', ['product'], 'id,pid,num');
        foreach ($list as $k => $v) {
            $v->title = $v->product->title;
            $v->price = $v->product->price;
            $v->icon = $v->product->icon;
            $v->stock = $v->product->stock;
            unset($v->product);
        }
        return json(['code' => 1, 'msg' => 'success', 'result' => $list]);
    }

    public function add(): Json
    {
        $param = $this->request->post();
        if (!$param['num'] || $param['num'] <= 0) {
            return json(['code' => -1, 'msg' => '数量错误']);
        }
        return json(CartModel::add($this->user, $param['id'], $param['num']));

    }

    public function edit(): Json
    {
        $param = $this->request->post();
        return json(CartModel::edit($param['type'], $param['id'], $this->user->id));
    }

    public function submit()
    {
        $param = $this->request->post();
        if (!$param['cart_id']) {
            return json(['code' => 1, 'msg' => '请选择要结算的商品']);
        }
        $param['cart_id'] = explode(',', $param['cart_id']);
        return json(CartModel::submit($param, $this->user));
    }
}


